package com.ware.common;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.render.Render;
import com.ware.jfinal.plugin.shiro.SH;
import com.ware.jfinal.plugin.shiro.ShiroRealm.ShiroUser;

public class AuthInterceptor implements Interceptor{

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	public void intercept(ActionInvocation ai){
		Controller controller = ai.getController();		
		HttpServletRequest request=controller.getRequest();
		controller.setAttr("basePath", request.getScheme()+"://"+
				request.getServerName()+":"+request.getServerPort()+
					request.getContextPath()+"/");
		try {
			ShiroUser user = null;
			if(SH.isAuth()){			
				user = (ShiroUser)SH.getSubject().getPrincipal();
				controller.setAttr("user", user);
				controller.setAttr("isLogin", true);
			}
//			if(SH.isAuth()){				
//				controller.setAttr("user", (ShiroUser)SH.getSubject().getPrincipal());
//			}
			ai.invoke();			
		} catch (Exception e) {	
			// 统一异常处理
			logger.error(controller.getClass().getName(),e);
			Render render = controller.getRender();
			if(render == null){
				controller.renderFreeMarker("/WEB-INF/view/common/error.ftl");
			}
		
		}
	}
}
